import { configureStore, getDefaultMiddleware } from '@reduxjs/toolkit'
import { save, load } from 'redux-localstorage-simple'

import application from './application/reducer'
import { updateVersion } from './global/actions'
import user from './user/reducer'
import transactions from './transactions/reducer'
import swap from './swap/reducer'
import mint from './mint/reducer'
import lists from './lists/reducer'
import burn from './burn/reducer'
import multicall from './multicall/reducer'

// store中需要持久化的状态
// 分别是：用户设置，交易记录，代币列表
const PERSISTED_KEYS: string[] = ['user', 'transactions', 'lists']

// 添加数据持久化的中间件save
var middlewares: any[]
middlewares = getDefaultMiddleware({ thunk: false })
middlewares.push(save({ states: PERSISTED_KEYS }))

// 配置app的主store
const store = configureStore({
  //定义要绑定的状态
  reducer: {
    application,
    user,
    transactions,
    swap,
    mint,
    burn,
    multicall,
    lists
  },
  // 应用的所有中间件
  middleware: middlewares,
  // 初始化，从持久化的状态恢复
  preloadedState: load({ states: PERSISTED_KEYS })
})

// 发射更新版本的信号
store.dispatch(updateVersion())

export default store
// 取出app状态的方法
export type AppState = ReturnType<typeof store.getState>
// 更新app状态的方法
export type AppDispatch = typeof store.dispatch
